import * as request from 'request';
import * as urlLib from 'url';

export interface DouYinShareLinkParse {
    readonly origin: string; // 分享源字符串
    readonly url: string;    // 解析出来的网页地址
    playUrl: string;// 视频播放地址
}

interface IteminfoItemDef {
    video: {
        play_addr: {
            uri: string;
            url_list: string[];
        }
    }
}

interface IteminfoDef {
    status_code: number;
    item_list: IteminfoItemDef[];
}

const headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36',
};

/**
 * 正则分享字符串解析出地址
 */
function parseDouYinShare(douYin: string): string {
    // 体验一直被忽略的福州市科技馆。无论多大年纪愿我们保存探索的心！%卡遛虎纠 %原创 %福州科技馆 %遛娃%  https://v.douyin.com/JW81EL6/ 复制此链接，打开抖音搜索，直接观看视频！
    // 日本普通的一个住房（俗称一户建），内部参观视频，最后有价格，有问题请留言哦%日本 %一户建 %日本大阪买房  https://v.douyin.com/JWTo1VA/ 覆制此链接，打开Dou吟搜索，直接观看视频！
    const reg = /(?:(https?|ftp|file):)?\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g; // 匹配 https://  ftp://  file://  这样开头的链接

    // 体验一直被忽略的福州市科技馆。无论多大年纪愿我们保存探索的心！%卡遛虎纠 %原创 %福州科技馆 %遛娃%；%%dZNyYa8q3f8%%打开Dou音搜索
    // const reg = /(%%)[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|](%%)/g; // 匹配 %% %% 中间包着的字符串
    const shortUrls = douYin.match(reg);
    if (null == shortUrls) {
        console.log(` _parseDouYinShare fail, douYin = [${douYin}]`);
        return '';
    }
    else if (!shortUrls[0]) {
        console.log(` _parseShareTextKuaiShou no data, douYin = [${douYin}]`);
        return '';
    }
    // console.log(' _parseDouYinShare result = ', shortUrls);
    return shortUrls[0];
}

/**
 * 爬虫去获得无水印视频的下载地址
 */
async function getPlayUrl(douYinShareUrl: string): Promise<string> {
    return new Promise((resolve, reject) => {
        request.get(douYinShareUrl, { headers: headers }, (err: any, res: request.Response) => {
            if (err) {
                return reject(` _getPlayUrl err = ${err}`);
            }
            const href = res.request.uri.href;
            if (!href) {
                return reject(' _getPlayUrl not have href ');
            }
            const url = urlLib.parse(href);
            if (!url.pathname) {
                return reject(' _getPlayUrl not url.pathname ');
            }
            const reg = /[0-9]+[0-9]/g; // 匹配纯数字的 id
            const ids = url.pathname?.match(reg); // pathname 是 '/share/video/6915971023628160268/' 这样格式的字符串
            if (!ids || !ids[0]) {
                console.error(' _getPlayUrl not reg match fail, pathname = ', url.pathname);
                return resolve('');
            }
            const itemUrl = `https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${ids[0]}`;
            request.get(itemUrl, { headers: headers }, (err: any, res: request.Response) => {
                if (err) {
                    console.error(' _getPlayUrl get href err = ', err);
                    return resolve('');
                }
                const body: IteminfoDef = JSON.parse(res.body);
                let realUrl = body.item_list[0].video.play_addr.url_list[0];
                realUrl = realUrl.replace('playwm', 'play'); // 这是为了下载无水印的视频
                const videoUrl = urlLib.parse(realUrl, true);
                const newSearchStr = `?video_id=${videoUrl.query.video_id}`; // 这是为了把链接里的分辨率参数去掉
                realUrl.replace(videoUrl.search?.toString, newSearchStr);
                return resolve(realUrl);
            });
        });
    });
}

async function main() {
    const douYinShare: string[] = [
        '体验一直被忽略的福州市科技馆。无论多大年纪愿我们保存探索的心！%卡遛虎纠 %原创 %福州科技馆 %遛娃%  https://v.douyin.com/JW81EL6/ 复制此链接，打开抖音搜索，直接观看视频！',
    ];

    const results: DouYinShareLinkParse[] = [];
    for (let i = 0; i < douYinShare.length; i++) {
        const url = parseDouYinShare(douYinShare[i]);
        const d: DouYinShareLinkParse = {
            origin: douYinShare[i],
            url: url,
            playUrl: '',
        };
        results.push(d);
    }

    for (let i = 0; i < results.length; i++) {
        results[i].playUrl = await getPlayUrl(results[i].url);
    }

    // console.log(' result = ', results);
}
main();

// https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0300f290000bvt7e2datuf65lb1ilrg&ratio=720p&line=0
// 去掉 /playwm 中的 wm ,变成
// https://aweme.snssdk.com/aweme/v1/play/?video_id=v0300f290000bvt7e2datuf65lb1ilrg&ratio=720p&line=0